// AutoJS6 悬浮窗控制脚本 - 简化稳定版本
"ui";

// 版本信息 - 直接写在脚本内部
const CURRENT_VERSION = "1.0.3";
const REMOTE_VERSION_URL = "https://gitee.com/xuxinzhi2206/autojs/raw/master/main.js";

// 当前版本更新内容
const CURRENT_UPDATE_CONTENT = `
版本 1.0.0 (2024-01-01)
- 初始版本发布
- 实现悬浮窗控制功能
- 添加权限检查功能
- 基础UI界面设计
- 优化界面布局，权限状态智能显示
`;

// 完整更新历史
const UPDATE_HISTORY = `
版本 1.0.1 (2024-01-15)
- 新增热更新功能，支持自动检测和更新脚本
- 修复网络请求主线程阻塞问题
- 添加更新内容显示功能
- 优化用户体验，增加更新提示弹框
- 修复悬浮窗权限检查问题
- 改进错误处理机制

版本 1.0.0 (2024-01-01)
- 初始版本发布
- 实现悬浮窗控制功能
- 添加权限检查功能
- 基础UI界面设计
- 优化界面布局，权限状态智能显示
`;

let floatingWindow = null;
let isFloatingWindowOpen = false;
let hasPermission = false;
const store = storages.create("autojs6_tool_settings");

// 动作引擎与流程数据
const FLOW_STORAGE_KEY = "flow_steps";
let flowSteps = store.get(FLOW_STORAGE_KEY, []);
let isFlowRunning = false;
let hasScreenCapture = false;

function saveFlow() {
    store.put(FLOW_STORAGE_KEY, flowSteps);
}

function ensureScreenCapture() {
    if (hasScreenCapture) return true;
    try {
        hasScreenCapture = requestScreenCapture(false);
        if (!hasScreenCapture) appendLog("未授予截屏权限");
    } catch (e) {
        appendLog("请求截屏权限失败: " + e.message);
        hasScreenCapture = false;
    }
    return hasScreenCapture;
}

function stepToSummary(step, index) {
    let title = (index + 1) + ". " + step.type;
    let subtitle = "";
    switch (step.type) {
        case "点击":
            subtitle = "x=" + step.x + ", y=" + step.y; break;
        case "滑动":
            subtitle = "(" + step.x1 + "," + step.y1 + ") → (" + step.x2 + "," + step.y2 + ") d=" + step.duration + "ms"; break;
        case "延迟":
            subtitle = step.ms + "ms"; break;
        case "打开应用":
            subtitle = step.appName; break;
        case "返回": subtitle = "系统返回"; break;
        case "主页": subtitle = "回到桌面"; break;
        case "提示": subtitle = step.text; break;
        case "截图": subtitle = step.path || "保存到默认目录"; break;
        case "图片识别点击": subtitle = (step.path || "(未设置图片)") + ", sim=" + (step.similarity || 0.8); break;
        case "文本匹配点击": subtitle = step.text + ", t=" + (step.timeout || 5000) + "ms"; break;
        case "滚动": subtitle = step.direction || "down"; break;
        case "区域随机点击": subtitle = "x=" + step.x + ",y=" + step.y + ",w=" + step.w + ",h=" + step.h; break;
        default: subtitle = JSON.stringify(step);
    }
    return { title: title, subtitle: subtitle };
}

function renderFlowList() {
    if (!ui.flowList) return;
    let data = flowSteps.map((s, i) => ({
        title: stepToSummary(s, i).title,
        subtitle: stepToSummary(s, i).subtitle
    }));
    ui.flowList.setDataSource(data);
}

function addStepDialog() {
    let items = [
        "点击",
        "滑动",
        "延迟",
        "打开应用",
        "返回",
        "主页",
        "提示",
        "截图",
        "图片识别点击",
        "文本匹配点击",
        "滚动",
        "区域随机点击"
    ];
    dialogs.select("选择动作", items).then(i => {
        if (i < 0) return;
        let action = items[i];
        switch (action) {
            case "点击":
                showParamDialog("点击坐标", [
                    { id: "x", hint: "x 像素", def: "100" },
                    { id: "y", hint: "y 像素", def: "200" }
                ], vals => {
                    flowSteps.push({ type: "点击", x: parseInt(vals.x), y: parseInt(vals.y) });
                    saveFlow(); renderFlowList();
                });
                break;
            case "滑动":
                showParamDialog("滑动", [
                    { id: "x1", hint: "起点 x", def: "100" },
                    { id: "y1", hint: "起点 y", def: "400" },
                    { id: "x2", hint: "终点 x", def: "100" },
                    { id: "y2", hint: "终点 y", def: "100" },
                    { id: "duration", hint: "时长 ms", def: "500" }
                ], vals => {
                    flowSteps.push({ type: "滑动", x1: parseInt(vals.x1), y1: parseInt(vals.y1), x2: parseInt(vals.x2), y2: parseInt(vals.y2), duration: parseInt(vals.duration) });
                    saveFlow(); renderFlowList();
                });
                break;
            case "延迟":
                showParamDialog("延迟", [ { id: "ms", hint: "毫秒", def: "1000" } ], vals => {
                    flowSteps.push({ type: "延迟", ms: parseInt(vals.ms) });
                    saveFlow(); renderFlowList();
                });
                break;
            case "打开应用":
                showParamDialog("打开应用", [ { id: "appName", hint: "应用名，如 微信", def: "" } ], vals => {
                    flowSteps.push({ type: "打开应用", appName: String(vals.appName || "") });
                    saveFlow(); renderFlowList();
                });
                break;
            case "返回":
                flowSteps.push({ type: "返回" }); saveFlow(); renderFlowList(); break;
            case "主页":
                flowSteps.push({ type: "主页" }); saveFlow(); renderFlowList(); break;
            case "提示":
                showParamDialog("提示", [ { id: "text", hint: "提示内容", def: "Hello" } ], vals => {
                    flowSteps.push({ type: "提示", text: String(vals.text || "") });
                    saveFlow(); renderFlowList();
                });
                break;
            case "截图":
                showParamDialog("截图", [ { id: "path", hint: "保存路径(可留空)", def: "" } ], vals => {
                    flowSteps.push({ type: "截图", path: String(vals.path || "") });
                    saveFlow(); renderFlowList();
                });
                break;
            case "图片识别点击":
                showParamDialog("图片识别点击", [
                    { id: "path", hint: "图片路径 /sdcard/xxx.png", def: "" },
                    { id: "similarity", hint: "相似度 0.0-1.0", def: "0.8" },
                    { id: "timeout", hint: "超时 ms", def: "5000" }
                ], vals => {
                    flowSteps.push({ type: "图片识别点击", path: String(vals.path || ""), similarity: parseFloat(vals.similarity || "0.8"), timeout: parseInt(vals.timeout || "5000") });
                    saveFlow(); renderFlowList();
                });
                break;
            case "文本匹配点击":
                showParamDialog("文本匹配点击", [
                    { id: "text", hint: "要匹配的文本", def: "" },
                    { id: "timeout", hint: "超时 ms", def: "5000" }
                ], vals => {
                    flowSteps.push({ type: "文本匹配点击", text: String(vals.text || ""), timeout: parseInt(vals.timeout || "5000") });
                    saveFlow(); renderFlowList();
                });
                break;
            case "滚动":
                showParamDialog("滚动", [ { id: "direction", hint: "down/up", def: "down" } ], vals => {
                    flowSteps.push({ type: "滚动", direction: (String(vals.direction || "down").toLowerCase()) });
                    saveFlow(); renderFlowList();
                });
                break;
            case "区域随机点击":
                showParamDialog("区域随机点击", [
                    { id: "x", hint: "区域 x", def: "100" },
                    { id: "y", hint: "区域 y", def: "300" },
                    { id: "w", hint: "宽度 w", def: "200" },
                    { id: "h", hint: "高度 h", def: "100" }
                ], vals => {
                    flowSteps.push({ type: "区域随机点击", x: parseInt(vals.x), y: parseInt(vals.y), w: parseInt(vals.w), h: parseInt(vals.h) });
                    saveFlow(); renderFlowList();
                });
                break;
        }
    });
}

function showParamDialog(title, fields, onOk) {
    let layout = <vertical padding="16">
        {fields.map(f => (
            <input id={f.id} hint={f.hint} text={f.def}/>
        ))}
    </vertical>;
    let d = dialogs.build({ title: title, customView: layout, positive: "确定", negative: "取消" });
    d.on("positive", function() {
        let vals = {};
        fields.forEach(f => { vals[f.id] = String(layout[f.id].text()); });
        try { onOk && onOk(vals); } catch (e) { toast("参数错误: " + e.message); }
    });
    d.show();
}

function runFlow() {
    if (isFlowRunning) { toast("已在运行"); return; }
    if (!flowSteps.length) { toast("没有步骤"); return; }
    isFlowRunning = true;
    appendLog("开始运行流程，共 " + flowSteps.length + " 步");
    threads.start(function() {
        try {
            for (let i = 0; i < flowSteps.length; i++) {
                let s = flowSteps[i];
                appendLog("执行第" + (i+1) + "步: " + s.type);
                runStep(s);
            }
            appendLog("流程完成");
        } catch (e) {
            appendLog("流程错误: " + e.message);
        } finally {
            isFlowRunning = false;
        }
    });
}

function runStep(s) {
    switch (s.type) {
        case "点击":
            press(parseInt(s.x), parseInt(s.y), 50);
            sleep(200);
            break;
        case "滑动":
            swipe(s.x1, s.y1, s.x2, s.y2, Math.max(1, s.duration || 500));
            sleep(200);
            break;
        case "延迟":
            sleep(Math.max(0, s.ms || 0));
            break;
        case "打开应用":
            if (s.appName) app.launchApp(String(s.appName));
            sleep(800);
            break;
        case "返回": back(); sleep(200); break;
        case "主页": home(); sleep(400); break;
        case "提示": toast(String(s.text || "")); sleep(200); break;
        case "截图":
            if (ensureScreenCapture()) {
                let img = images.captureScreen();
                if (img) {
                    let path = s.path && s.path.trim().length > 0 ? s.path : "/sdcard/AutoJS6/capture_" + Date.now() + ".png";
                    files.ensureDir(files.dirname(path));
                    images.save(img, path, "png", 100);
                    img.recycle();
                    appendLog("截图已保存: " + path);
                }
            }
            break;
        case "图片识别点击":
            if (!s.path) { appendLog("未设置图片路径"); break; }
            if (!ensureScreenCapture()) break;
            let target = images.read(s.path);
            if (!target) { appendLog("读取目标图片失败"); break; }
            let screen = images.captureScreen();
            if (!screen) { appendLog("截屏失败"); target.recycle(); break; }
            let startTs = Date.now(); let pt = null;
            let sim = typeof s.similarity === "number" ? s.similarity : 0.8;
            let timeout = s.timeout || 5000;
            while (Date.now() - startTs < timeout) {
                pt = images.findImage(screen, target, { threshold: 1 - sim });
                if (pt) break;
                sleep(300);
                screen.recycle();
                screen = images.captureScreen();
            }
            if (pt) { press(pt.x + target.getWidth()/2, pt.y + target.getHeight()/2, 60); appendLog("图片点击: (" + pt.x + "," + pt.y + ")"); }
            else { appendLog("未匹配到图片"); }
            if (screen) screen.recycle();
            target.recycle();
            break;
        case "文本匹配点击":
            try {
                let timeoutMs = s.timeout || 5000;
                let node = text(s.text).findOne(timeoutMs) || desc(s.text).findOne(timeoutMs);
                if (node) {
                    let b = node.bounds();
                    press(b.centerX(), b.centerY(), 60);
                } else {
                    appendLog("未找到文本: " + s.text);
                }
            } catch (e) { appendLog("文本匹配失败: " + e.message); }
            break;
        case "滚动":
            if (String(s.direction||"down") === "up") scrollUp(); else scrollDown();
            sleep(300);
            break;
        case "区域随机点击":
            let rx = s.x + Math.floor(Math.random() * Math.max(1, s.w));
            let ry = s.y + Math.floor(Math.random() * Math.max(1, s.h));
            press(rx, ry, 50);
            sleep(150);
            break;
        default:
            appendLog("未知动作: " + s.type);
            break;
    }
}

// 热更新功能 - 在子线程中执行网络请求
function checkForUpdates() {
    console.log("检查更新中...");
    toast("正在检查更新...");
    appendLog("开始检查更新");
    
    // 在子线程中执行网络请求
    threads.start(function() {
        try {
            // 从网络获取最新版本的脚本内容
            let response = http.get(REMOTE_VERSION_URL);
            if (response.statusCode === 200) {
                let remoteContent = response.body.string();
                
                // 从远程脚本中提取版本号和更新内容
                let versionMatch = remoteContent.match(/const CURRENT_VERSION = "([^"]+)"/);
                let currentUpdateMatch = remoteContent.match(/const CURRENT_UPDATE_CONTENT = `([\s\S]*?)`;/);
                let historyMatch = remoteContent.match(/const UPDATE_HISTORY = `([\s\S]*?)`;/);
                
                if (versionMatch) {
                    let remoteVersion = versionMatch[1];
                    let currentVersion = CURRENT_VERSION;
                    let currentUpdate = currentUpdateMatch ? currentUpdateMatch[1].trim() : "暂无更新说明";
                    let updateHistory = historyMatch ? historyMatch[1].trim() : "暂无历史记录";
                    
                    console.log("当前版本:", currentVersion);
                    console.log("远程版本:", remoteVersion);
                    
                    // 比较版本号
                    if (compareVersions(remoteVersion, currentVersion) > 0) {
                        console.log("发现新版本，显示更新提示");
                        // 在主线程中显示对话框
                        ui.run(function() {
                            showUpdateDialog(remoteVersion, remoteContent, currentUpdate, updateHistory);
                        });
                        appendLog("发现新版本: " + remoteVersion);
                    } else {
                        console.log("已是最新版本");
                        ui.run(function() {
                            toast("已是最新版本");
                        });
                        appendLog("已是最新版本: " + currentVersion);
                    }
                } else {
                    console.log("无法解析远程版本号");
                    ui.run(function() {
                        toast("检查更新失败：无法获取版本信息");
                    });
                    appendLog("检查更新失败：无法获取版本信息");
                }
            } else {
                console.log("网络请求失败:", response.statusCode);
                ui.run(function() {
                    toast("检查更新失败：网络连接错误");
                });
                appendLog("检查更新失败：网络连接错误");
            }
        } catch (e) {
            console.error("检查更新失败:", e.message);
            ui.run(function() {
                toast("检查更新失败: " + e.message);
            });
            appendLog("检查更新失败: " + e.message);
        }
    });
}

// 版本号比较函数
function compareVersions(version1, version2) {
    let v1parts = version1.split('.').map(Number);
    let v2parts = version2.split('.').map(Number);
    
    for (let i = 0; i < Math.max(v1parts.length, v2parts.length); i++) {
        let v1part = v1parts[i] || 0;
        let v2part = v2parts[i] || 0;
        
        if (v1part > v2part) return 1;
        if (v1part < v2part) return -1;
    }
    return 0;
}

// 显示更新对话框
function showUpdateDialog(remoteVersion, remoteContent, currentUpdate, updateHistory) {
    // 创建带Tab的对话框
    let dialog = dialogs.build({
        title: "发现新版本",
        content: "",
        positive: "立即更新",
        negative: "暂不更新",
        neutral: "查看历史"
    });
    
    // 创建Tab布局
    let tabLayout = (
        <vertical>
            <horizontal>
                <button id="currentTab" text="当前更新" textSize="14sp" 
                        textColor="#FFFFFF" background="#2196F3" 
                        padding="8" margin="4" weight="1"/>
                <button id="historyTab" text="更新历史" textSize="14sp" 
                        textColor="#666666" background="#F5F5F5" 
                        padding="8" margin="4" weight="1"/>
            </horizontal>
            <scroll>
                <text id="contentText" text={currentUpdate} textSize="14sp" 
                      textColor="#333333" margin="8"/>
            </scroll>
        </vertical>
    );
    
    // 设置对话框内容
    dialog.setCustomView(tabLayout);
    
    // Tab切换逻辑
    let currentTabBtn = tabLayout.currentTab;
    let historyTabBtn = tabLayout.historyTab;
    let contentText = tabLayout.contentText;
    
    currentTabBtn.click(function() {
        currentTabBtn.setTextColor(colors.parseColor("#FFFFFF"));
        currentTabBtn.setBackgroundColor(colors.parseColor("#2196F3"));
        historyTabBtn.setTextColor(colors.parseColor("#666666"));
        historyTabBtn.setBackgroundColor(colors.parseColor("#F5F5F5"));
        contentText.setText(currentUpdate);
    });
    
    historyTabBtn.click(function() {
        historyTabBtn.setTextColor(colors.parseColor("#FFFFFF"));
        historyTabBtn.setBackgroundColor(colors.parseColor("#2196F3"));
        currentTabBtn.setTextColor(colors.parseColor("#666666"));
        currentTabBtn.setBackgroundColor(colors.parseColor("#F5F5F5"));
        contentText.setText(updateHistory);
    });
    
    // 按钮事件
    dialog.on("positive", function() {
        downloadAndUpdate(remoteContent);
    });
    
    dialog.show();
}

// 下载并更新 - 在子线程中执行
function downloadAndUpdate(remoteContent) {
    toast("开始更新...");
    
    // 在子线程中执行下载和更新
    threads.start(function() {
        try {
            // 备份当前文件
            let currentFile = files.path("./main.js");
            let backupFile = files.path("./main.js.backup");
            files.write(backupFile, files.read(currentFile));
            
            // 写入新版本
            files.write(currentFile, remoteContent);
            
            ui.run(function() {
                toast("更新完成！脚本将在3秒后重启");
            });
            
            // 延迟重启
            setTimeout(function() {
                // 重新加载脚本
                engines.execScriptFile(currentFile);
                exit();
            }, 3000);
            
        } catch (e) {
            ui.run(function() {
                toast("更新失败: " + e.message);
            });
            console.error("更新错误:", e);
        }
    });
}

// 新增：日志追加工具
function appendLog(message) {
    try {
        let timestamp = new Date().toLocaleString();
        ui.run(function() {
            if (ui.logText) {
                let prev = ui.logText.text();
                ui.logText.setText((prev ? prev + "\n" : "") + "[" + timestamp + "] " + message);
            }
        });
    } catch (e) {
        // 忽略日志错误
    }
}

// 创建主页面UI（改为包含五个页面的 Tabs 框架）
ui.layout(
    <vertical>
        <tabs id="tabs"/>
        <viewpager id="viewpager">
            <scroll>
                <vertical padding="16">
                    <text text="AutoJS6 悬浮窗控制" textSize="24sp" textColor="#333333" gravity="center" margin="16"/>
                    
                    <card cardCornerRadius="8dp" cardElevation="4dp" margin="8">
                        <vertical padding="16">
                            <text text="权限状态" textSize="18sp" textColor="#666666" margin="8"/>
                            <text id="permissionStatus" text="检查中..." textSize="16sp" textColor="#FF9800" margin="8"/>
                            <button id="checkPermissionBtn" text="去设置权限" textSize="16sp" 
                                    textColor="#FFFFFF" background="#2196F3" 
                                    padding="12" margin="8" visibility="gone"/>
                        </vertical>
                    </card>
                    
                    <card cardCornerRadius="8dp" cardElevation="4dp" margin="8">
                        <vertical padding="16">
                            <text text="悬浮窗控制" textSize="18sp" textColor="#666666" margin="8"/>
                            <text id="statusText" text="悬浮窗已关闭" textSize="16sp" textColor="#FF5722" margin="8"/>
                            
                            <button id="toggleBtn" text="开启悬浮窗" textSize="16sp" 
                                    textColor="#FFFFFF" background="#4CAF50" 
                                    padding="12" margin="8" enabled="false"/>
                        </vertical>
                    </card>
                    
                    <card cardCornerRadius="8dp" cardElevation="4dp" margin="8">
                        <vertical padding="16">
                            <text text="使用说明" textSize="18sp" textColor="#666666" margin="8"/>
                            <text text="1. 首先确保悬浮窗权限已开启\n2. 开启权限后可以创建悬浮窗\n3. 悬浮窗上有关闭按钮\n4. 点击'检查更新'可以检查新版本\n5. 更新历史在设置页" 
                                  textSize="14sp" textColor="#888888" margin="8"/>
                        </vertical>
                    </card>
                </vertical>
            </scroll>
            
            <vertical padding="8">
                <horizontal>
                    <button id="addStepBtn" text="添加步骤" textSize="14sp" textColor="#FFFFFF" background="#4CAF50" padding="10" margin="8"/>
                    <button id="runFlowBtn" text="运行流程" textSize="14sp" textColor="#FFFFFF" background="#2196F3" padding="10" margin="8"/>
                    <button id="clearFlowBtn" text="清空" textSize="14sp" textColor="#FFFFFF" background="#9E9E9E" padding="10" margin="8"/>
                </horizontal>
                <list id="flowList">
                    <horizontal padding="12">
                        <vertical w="*">
                            <text text="{{title}}" textSize="16sp" textColor="#333333"/>
                            <text text="{{subtitle}}" textSize="12sp" textColor="#888888"/>
                        </vertical>
                    </horizontal>
                </list>
            </vertical>
            
            <vertical padding="16">
                <text text="计划任务（占位）" textSize="16sp" textColor="#666666" margin="8"/>
                <text text="未来可加入定时器、触发器等" textSize="14sp" textColor="#888888" margin="8"/>
            </vertical>
            
            <vertical padding="8">
                <horizontal>
                    <button id="clearLogBtn" text="清空" textSize="14sp" textColor="#FFFFFF" background="#9E9E9E" padding="8" margin="8"/>
                    <button id="copyLogBtn" text="复制" textSize="14sp" textColor="#FFFFFF" background="#607D8B" padding="8" margin="8"/>
                </horizontal>
                <scroll>
                    <text id="logText" text="" textSize="12sp" textColor="#444444" margin="8"/>
                </scroll>
            </vertical>
            
            <scroll>
                <vertical padding="16">
                    <text text="设置" textSize="18sp" textColor="#666666" margin="8"/>
                    <card cardCornerRadius="8dp" cardElevation="4dp" margin="8">
                        <vertical padding="16">
                            <text text="版本信息" textSize="18sp" textColor="#666666" margin="8"/>
                            <text text={"当前版本: " + CURRENT_VERSION} textSize="14sp" textColor="#888888" margin="8"/>
                            <horizontal>
                                <button id="checkUpdateBtn" text="检查更新" textSize="16sp" 
                                        textColor="#FFFFFF" background="#FF9800" 
                                        padding="12" margin="8" weight="1"/>
                                <button id="viewHistoryBtn" text="更新历史" textSize="16sp" 
                                        textColor="#FFFFFF" background="#9C27B0" 
                                        padding="12" margin="8" weight="1"/>
                            </horizontal>
                        </vertical>
                    </card>
                    <checkbox id="autoUpdateSwitch" text="启动时自动检查更新" textSize="16sp" margin="8"/>
                    <checkbox id="autoFloatSwitch" text="启动后自动打开悬浮窗（需权限）" textSize="16sp" margin="8"/>
                    <button id="saveSettingsBtn" text="保存设置" textSize="16sp" textColor="#FFFFFF" background="#2196F3" padding="12" margin="8"/>
                </vertical>
            </scroll>
        </viewpager>
    </vertical>
);

// 绑定 Tabs 与页标题
ui.viewpager.setTitles(["首页", "脚本", "计划", "日志", "设置"]);
ui.tabs.setupWithViewPager(ui.viewpager);
// 美化 Tabs：设置深色背景与可读文字颜色
ui.run(function() {
    try {
        ui.tabs.setBackgroundColor(colors.parseColor("#2196F3"));
        if (ui.tabs.setSelectedTabIndicatorColor) {
            ui.tabs.setSelectedTabIndicatorColor(colors.parseColor("#FFFFFF"));
        }
        if (ui.tabs.setTabTextColors) {
            ui.tabs.setTabTextColors(colors.parseColor("#BBDEFB"), colors.parseColor("#FFFFFF"));
        }
    } catch (e) {}
});

// 初始化设置开关状态
if (ui.autoUpdateSwitch) ui.autoUpdateSwitch.checked = store.get("autoUpdate", true);
if (ui.autoFloatSwitch) ui.autoFloatSwitch.checked = store.get("autoOpenFloat", false);

// 保存设置
if (ui.saveSettingsBtn) ui.saveSettingsBtn.click(function() {
    store.put("autoUpdate", ui.autoUpdateSwitch.checked);
    store.put("autoOpenFloat", ui.autoFloatSwitch.checked);
    toast("设置已保存");
    appendLog("设置已保存");
});

// 流程编辑器事件
if (ui.addStepBtn) ui.addStepBtn.click(addStepDialog);
if (ui.clearFlowBtn) ui.clearFlowBtn.click(function() { flowSteps = []; saveFlow(); renderFlowList(); toast("已清空"); });
if (ui.runFlowBtn) ui.runFlowBtn.click(runFlow);
if (ui.flowList) {
    ui.flowList.on("item_long_click", function(item, i) {
        dialogs.confirm("删除步骤", item.title).then(ok => { if (ok) { flowSteps.splice(i,1); saveFlow(); renderFlowList(); }});
        return true;
    });
}
renderFlowList();

// 检查权限按钮点击事件
ui.checkPermissionBtn.click(function() {
    openPermissionSettings();
});

// 悬浮窗控制按钮点击事件
ui.toggleBtn.click(function() {
    if (isFloatingWindowOpen) {
        closeFloatingWindow();
    } else {
        openFloatingWindow();
    }
});

// 显示历史更新对话框
function showHistoryDialog() {
    dialogs.build({
        title: "更新历史",
        content: UPDATE_HISTORY,
        positive: "确定"
    }).show();
}

// 打开权限设置
function openPermissionSettings() {
    try {
        app.startActivity({
            action: "android.settings.action.MANAGE_OVERLAY_PERMISSION",
            data: "package:" + context.getPackageName()
        });
        toast("请在设置中开启悬浮窗权限，然后重新运行脚本");
    } catch (e) {
        app.startActivity("android.settings.SETTINGS");
        toast("请手动找到悬浮窗权限并开启");
    }
}

// 检查悬浮窗权限
function checkPermission() {
    try {
        // AutoJS6 权限检查
        if (typeof floaty !== 'undefined' && floaty.checkPermission) {
            hasPermission = floaty.checkPermission();
        } else {
            // 备用检查方法
            hasPermission = true;
        }
        
        if (hasPermission) {
            ui.permissionStatus.setText("✅ 悬浮窗权限已开启");
            ui.permissionStatus.setTextColor(colors.parseColor("#4CAF50"));
            ui.toggleBtn.setEnabled(true);
            ui.checkPermissionBtn.setVisibility(8); // GONE
            toast("权限检查通过，可以创建悬浮窗");
            appendLog("权限检查通过");
        } else {
            ui.permissionStatus.setText("❌ 悬浮窗权限未开启");
            ui.permissionStatus.setTextColor(colors.parseColor("#FF5722"));
            ui.toggleBtn.setEnabled(false);
            ui.checkPermissionBtn.setVisibility(0); // VISIBLE
            toast("需要开启悬浮窗权限");
            appendLog("悬浮窗权限未开启");
        }
    } catch (e) {
        ui.permissionStatus.setText("⚠️ 权限检查失败");
        ui.permissionStatus.setTextColor(colors.parseColor("#FF9800"));
        ui.checkPermissionBtn.setVisibility(0); // VISIBLE
        toast("权限检查失败: " + e.message);
        console.error("权限检查错误:", e);
        appendLog("权限检查失败: " + e.message);
    }
}

// 开启悬浮窗
function openFloatingWindow() {
    try {
        if (floatingWindow) {
            floatingWindow.close();
            floatingWindow = null;
        }
        
        // 创建悬浮窗
        floatingWindow = floaty.window(
            <vertical bg="#FF5722" padding="8" alpha="0.9">
                <text text="悬浮窗" textColor="#FFFFFF" textSize="14sp" gravity="center"/>
                <text text="点击关闭" textColor="#FFFFFF" textSize="10sp" gravity="center"/>
                <button id="closeBtn" text="关闭" textSize="12sp" 
                        textColor="#FFFFFF" background="#F44336" 
                        padding="4" margin="2"/>
            </vertical>
        );
        
        // 设置位置和大小
        floatingWindow.setPosition(100, 300);
        floatingWindow.setSize(120, 80);
        
        // 关闭按钮事件
        floatingWindow.closeBtn.click(function() {
            closeFloatingWindow();
        });
        
        // 更新状态
        isFloatingWindowOpen = true;
        ui.statusText.setText("悬浮窗已开启");
        ui.statusText.setTextColor(colors.parseColor("#4CAF50"));
        ui.toggleBtn.setText("关闭悬浮窗");
        ui.toggleBtn.setBackgroundColor(colors.parseColor("#FF5722"));
        
        toast("悬浮窗创建成功！");
        appendLog("悬浮窗创建成功");
        
    } catch (e) {
        toast("创建悬浮窗失败: " + e.message);
        console.error("错误:", e);
        appendLog("创建悬浮窗失败: " + e.message);
    }
}

// 关闭悬浮窗
function closeFloatingWindow() {
    try {
        if (floatingWindow) {
            floatingWindow.close();
            floatingWindow = null;
        }
        
        isFloatingWindowOpen = false;
        ui.statusText.setText("悬浮窗已关闭");
        ui.statusText.setTextColor(colors.parseColor("#FF5722"));
        ui.toggleBtn.setText("开启悬浮窗");
        ui.toggleBtn.setBackgroundColor(colors.parseColor("#4CAF50"));
        
        toast("悬浮窗已关闭");
        appendLog("悬浮窗已关闭");
        
    } catch (e) {
        toast("关闭失败: " + e.message);
        appendLog("关闭悬浮窗失败: " + e.message);
    }
}

// 退出时清理
events.on("exit", function() {
    if (floatingWindow) {
        floatingWindow.close();
    }
});

// 应用启动时自动检查权限和更新（改：尊重设置）
setTimeout(function() {
    checkPermission();
    // 自动打开悬浮窗（根据设置）
    setTimeout(function() {
        if (store.get("autoOpenFloat", false) && hasPermission) {
            openFloatingWindow();
            appendLog("根据设置自动打开悬浮窗");
        }
    }, 800);
    // 延迟检查更新，依据设置
    if (store.get("autoUpdate", true)) {
        setTimeout(function() {
            checkForUpdates();
        }, 2000);
    }
}, 1000);

toast("应用已启动");
